from django.http import JsonResponse

# Create your views here.
from products.models import Product, ProductImage


def single(request, slug):
    try:
        product = Product.objects.get(slug=slug)
        images = ProductImage.objects.filter(product=product)
        context = {'product': product.to_dict(), "images": [img.to_dict() for img in images]}
        return JsonResponse(context)
    except Exception as e:
        print(e)
        return JsonResponse({'status': 404})


def all(request):
    products = Product.objects.all()
    if products:
        content = {'products': [product.to_dict() for product in products]}
    else:
        content = {}

    return JsonResponse(content)


def search(request):
    q = request.GET.get('q')
    if q:
        products = Product.objects.filter(title__icontains=q)
        return JsonResponse({'products': products})

    return JsonResponse({"msg": "missing search keywords"})
